package com.example.myapplication;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class CurrencyAdapter extends RecyclerView.Adapter<CurrencyAdapter.ViewHolder> {
    private final OnCurrencyClickListener listener;
    private List<Currency> currencyList;

    public CurrencyAdapter(OnCurrencyClickListener listener) {
        this.listener = listener;
    }

    public void setData(List<Currency> data) {
        this.currencyList = data;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.currency_item, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Currency currency = currencyList.get(position);
        holder.name.setText(currency.getCurrencyName());
        holder.rate.setText(String.format("卖出价：1 CNY = %.4f %s",
                currency.getSellRate(), currency.getCurrencyCode()));

        holder.itemView.setOnClickListener(v -> listener.onCurrencyClick(currency));
    }

    @Override
    public int getItemCount() {
        return currencyList != null ? currencyList.size() : 0;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView name;
        TextView rate;
        public ViewHolder(View itemView) {
            super(itemView);
            name = itemView.findViewById(R.id.tv_currency_name);
            rate = itemView.findViewById(R.id.tv_currency_rate);
        }
    }

    public interface OnCurrencyClickListener {
        void onCurrencyClick(Currency currency);
    }
}